<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="门店Logo" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="logo">
              <j-image-upload v-model="model.logo" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="门店登录账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="loginAccount">
              <a-input v-model="model.loginAccount" placeholder="请输入门店登录账号"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="门店登录密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pass">
              <a-input v-model="model.pass" placeholder="请输入门店登录密码"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="商户绑定appId" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="merchantAppid">
              <a-input v-model="model.merchantAppid" placeholder="请输入商户绑定appId"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="门店名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storeName">
              <a-input v-model="model.storeName" placeholder="请输入门店名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="门店描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.storeDescription" placeholder="请输入门店描述"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="平台描述" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="model.desList_label" placeholder="请输入平台描述" @blur="inputBlur" ></a-input>
              <div style="line-height: normal;color:#a7a4a4">(多个描述间使用“/”隔开，如：轻食/热门/卫生 表示3个描述标签。描述文字请不要使用/)</div>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="限购数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="limitNum">
              <a-input-number
                :min="-1"
                :precision="0"
                v-model="model.limitNum"
                placeholder="请输入限购,-1表示不限数量"
                style="width: 117px"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="门店菜品合作单价" :labelCol="labelCol" :wrapperCol="wrapperCol"
              :prop="model.customPriceFlag == '否' ? 'priceArray' : ''">
              <a-row type="flex" align="middle" style="margin-bottom: 5px" v-for="(item, index) in model.priceArray"
                :key="index">
                <a-input-number :min="0" :precision="2" style="width: 80px" @change="inputBlur"
                  v-model="model.priceArray[index]" />
                <a-button type="primary" icon="plus" style="margin-left: 5px" @click="addItem" />
                <a-button type="danger" icon="minus" v-if="index > 0" style="margin-left: 5px" @click="delItem(index)" />
              </a-row>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="开启自定义价格" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customPriceFlag">
              <a-radio-group v-model="model.customPriceFlag" button-style="solid">
                <a-radio-button value="否"> 否 </a-radio-button>
                <a-radio-button value="是"> 是 </a-radio-button>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="门店营业时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="businessHoursArray">
              <a-row v-for="item in 3" :key="item">
                {{ item }}
                <j-time @change="timeChange" date-format="HH:mm" v-model="model.businessHoursArray[item - 1].startTime" />
                -
                <j-time @change="timeChange" date-format="HH:mm" v-model="model.businessHoursArray[item - 1].endTime" />
              </a-row>
            </a-form-model-item>
          </a-col>

          <a-col :span="24">
            <a-form-model-item label="门店资质" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload v-model="model.qualifications" :is-multiple="true" :number="9" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="包装评分" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packagingScore">
              <a-input-number :min="0" :max="5" :precision="1" v-model="model.packagingScore" placeholder="请输入包装评分"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="分量评分" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="componentScore">
              <a-input-number :min="0" :max="5" :precision="1" v-model="model.componentScore" placeholder="请输入分量评分"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="口味评分" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flavorScore">
              <a-input-number :min="0" :max="5" :precision="1" v-model="model.flavorScore" placeholder="请输入口味评分"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="24">-->
          <!--            <a-form-model-item label="排序" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sort">-->
          <!--              <a-input-number v-model="model.sort" placeholder="请输入排序" style="width: 100%"/>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col :span="24">
            <a-form-model-item label="主营品类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="mainCategoriesId">
              <j-dict-select-tag v-model="model.mainCategoriesId" dict-code="HC_MAIN_CATEGORIES,NAME,ID"
                placeholder="请选择主营品类" @change="" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="所属站点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="siteId">
              <!--              <j-dict-select-tag v-model="model.siteId" dict-code="HC_SITE,NAME,ID" placeholder="请选择所属站点" @change=""/>-->
              <j-multi-select-tag @change="siteChange" v-model="model.siteId" dict-code="HC_SITE,NAME,ID"
                placeholder="请选择所属站点" />
              <a-row justify="space-between">
                <a-col :span="8" v-for="(item, index) in siteArray" >
                  <span :class='{siteActive: selectCurrentSiteId == item.siteId}' style='cursor:pointer'  @click='selectCurrentSiteId = item.siteId'>{{ item.siteName }}：</span>
                  <a-input-number :min="0" :precision="0" placeholder="排序" v-model="item.sort" />
                </a-col>

                <div style='clear:both;color:red'>若有增加或移除站点，请先点击“确定”按钮进行保存一次后，再编辑下面的大厦数据</div>

                <div v-for="(item, index) in addressMerchantRelations" class='hmf-item-addressMerchantRelations'>
                  <div>
                    <a-radio-group v-model="item.isOpen" button-style="solid" @change='changeBuildCactivation(item)'>
                      <a-radio-button value="true"> 启用 </a-radio-button>
                      <a-radio-button value="false"> 关闭 </a-radio-button>
                    </a-radio-group>
                  </div>
                  <div class='edifice' @click='clickAddressDetailsName(item)'>{{ item.addressDetailsName }}</div>
                  <div class='business'>营业时间</div>
                  <div>
                    <j-time  date-format="HH:mm" v-model="item.provideStartTime" :allowClear='false'/>
                    -
                    <j-time  date-format="HH:mm" v-model="item.provideEndTime" :allowClear='false'/>
                    
                  </div>
                    
                </div>



              </a-row>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>

    <HcMerchantAddressDetailModal 
      :show='addressDetail.show' 
      :title='addressDetail.addressName'
      :addressId='addressDetail.addressId' 
      :merchantId='addressDetail.merchantId' 
      @handleCloseDetailModal='handleCloseDetailModal'
      />
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
import { duplicateCheck } from '@api/api'
import HcMerchantAddressDetailModal from './HcMerchantAddressDetailModal.vue'

export default {
  name: 'HcMerchantForm',
  components: {
    HcMerchantAddressDetailModal: HcMerchantAddressDetailModal,
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      model: {
        customPriceFlag: '否',
        priceArray: [''],
        businessHoursArray: [{ startTime: '19:00', endTime: '10:10' }, {}, {}],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        logo: [{ required: true, message: '请输入门店LOGO!' }],
        storeDescription: [{ required: true, message: '请输入门店描述!' }],
        storeName: [{ required: true, message: '请输入门店名称!' }],
        priceArray: [
          { required: true, message: '请输入门店菜品合作单价!' },
          {
            validator: (rule, value, callback) => {
              let filter = this.model.priceArray.filter(Boolean)

              if (filter == null || filter.length == 0) {
                callback('请输入门店菜品合作单价')
              }

              callback()
            },
          },
        ],
        customPriceFlag: [{ required: true, message: '请输入开启自定义价格!' }],
        businessHoursBegin: [{ required: true, message: '请输入门店开始营业时间!' }],
        businessHoursArray: [
          { required: true, message: '请选择门店营业时间!' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
              } else {
                if (!this.model.businessHoursArray[0].startTime || !this.model.businessHoursArray[0].endTime) {
                  callback('请选择门店营业时间!')
                } else if (
                  (this.model.businessHoursArray[1].startTime && !this.model.businessHoursArray[1].endTime) ||
                  (!this.model.businessHoursArray[1].startTime && this.model.businessHoursArray[1].endTime) ||
                  (this.model.businessHoursArray[2].startTime && !this.model.businessHoursArray[2].endTime) ||
                  (!this.model.businessHoursArray[2].startTime && this.model.businessHoursArray[2].endTime)
                ) {
                  callback('请选择门店营业时间!')
                } else if (
                  this.model.businessHoursArray[0].startTime == this.model.businessHoursArray[0].endTime ||
                  (this.model.businessHoursArray[1].startTime &&
                    this.model.businessHoursArray[1].endTime &&
                    this.model.businessHoursArray[1].startTime == this.model.businessHoursArray[1].endTime) ||
                  (this.model.businessHoursArray[2].startTime &&
                    this.model.businessHoursArray[2].endTime &&
                    this.model.businessHoursArray[2].startTime == this.model.businessHoursArray[2].endTime)
                ) {
                  callback('开始时间不能和结束时间一样!')
                } else {
                  callback()
                }
              }
            },
          },
        ],
        afternoonHoursEnd: [
          { required: true, message: '请选择门店下午营业时间!' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
              } else {
                if (!this.model.afternoonHoursBegin || !this.model.afternoonHoursEnd) {
                  callback('请选择门店下午营业时间!')
                } else {
                  callback()
                }
              }
            },
          },
        ],
        qualifications: [{ required: true, message: '请输入门店资质!' }],
        loginAccount: [
          { required: true, message: '请输入门店登录账号!' },
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback()
              } else {
                var reg_tel = /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;    //11位手机号码正则
                if (!reg_tel.test(value)) {
                  console.log('5555')
                  callback('请输入正确格式的手机号码!')
                } else {
                  var params = {
                    tableName: 'HC_MERCHANT',
                    fieldName: 'LOGIN_ACCOUNT',
                    fieldVal: value,
                    delFlag: 0,
                    dataId: this.model.id,
                  }
                  duplicateCheck(params).then((res) => {
                    if (res.success) {
                      callback()
                    } else {
                      callback('门店登录账号已存在!')
                    }
                  })
                }
              }
            },
          },
        ],
        pass: [{ required: true, message: '请输入门店登录密码' }],
        packagingScore: [{ required: true, message: '请输入包装评分!' }],
        componentScore: [{ required: true, message: '请输入分量评分!' }],
        flavorScore: [{ required: true, message: '请输入口味评分!' }],
        sort: [{ required: true, message: '请输入排序!' }],
        mainCategoriesId: [{ required: true, message: '请选择主营品类!' }],
        siteId: [{ required: true, message: '请选择所属站点!' }],
        limitNum: [{ required: true, message: '请输入限购，-1表示不限数量!'}],
      },
      url: {
        add: '/hc/hcMerchant/add',
        edit: '/hc/hcMerchant/edit',
        queryById: '/hc/hcMerchant/queryById',
      },
      siteArray: [],

      // 大厦详情
      addressDetail: {
        show: false,
        addressId: '',
        merchantId: '',
        addressName: '',
      },
      selectCurrentSiteId: '',
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    addressMerchantRelations() {
      let resultArr = [];
      let siteList = this.siteArray || [];
      if (siteList.length == 0) {
        return [];
      }
      this.selectCurrentSiteId = this.selectCurrentSiteId || siteList[0].siteId
      siteList.forEach(site => {
        if (site.siteId == this.selectCurrentSiteId) {
          let relaList = site.addressMerchantRelations || [];
          relaList.forEach(rela => {
            rela.siteId = site.siteId;
            rela.siteName = site.siteName;
            resultArr.push(rela);
          })
        }
      })
      console.log('addressMerchantRelations--->', resultArr)
      return resultArr;
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  mounted() {
    this.$nextTick(() => {
      this.model.businessHoursArray[0] = { startTime: '19:00', endTime: '10:10' }
      this.$forceUpdate()
    })
  },
  methods: {
    timeChange() {
      this.$forceUpdate()
    },
    siteChange(ids, array) {
      let siteArrayCache = []

      ids.split(',').forEach((siteId) => {
        let find = this.siteArray ? this.siteArray.find((el) => el.siteId == siteId) : undefined
        if (!find) {
          find = array.find((el) => el.value == siteId)
          siteArrayCache.push({ 
            siteId: find.value, 
            siteName: find.text, 
            addressMerchantRelations: find.addressMerchantRelations || []
          })
        } else {
          siteArrayCache.push(find)
        }
      })

      this.siteArray = siteArrayCache
      console.log(siteArrayCache)
      
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.model = Object.assign({}, record)

      if (this.model.storeUnitPrice) {
        this.model.priceArray = JSON.parse(this.model.storeUnitPrice)

        if (this.model.priceArray.length == 0) {
          this.model.priceArray.push('')
        }
      } else {
        this.model.priceArray = ['']
      }

      this.siteArray = this.model.hcSiteRelationList
      try {
        let arr = JSON.parse(this.model.businessHours)
        this.$nextTick(() => {
          this.model.businessHoursArray = arr;
          this.$forceUpdate()
        })

        console.log('6666', this.model.businessHoursArray)

        let number = 3 - this.model.businessHoursArray.length

        if (number > 0) {
          for (let i = 0; i < number; i++) {
            this.model.businessHoursArray.push({ startTime: '', endTime: '' })
          }
        }
      } catch (e) {
        this.model.businessHoursArray = [
          { startTime: '19:00', endTime: '10:10' },
          { startTime: '', endTime: '' },
          { startTime: '', endTime: '' },
        ]
      }

      console.log('aaabb--label')
      let desList = this.model.desList || [];
      this.model.desList_label = desList.join('/')
      this.visible = true
    },
    addItem() {
      this.model.priceArray.push('')
      this.$forceUpdate()
    },
    inputBlur() {
      this.$forceUpdate()
    },
    delItem(index) {
      this.model.priceArray.splice(index, 1)
      this.$forceUpdate()
    },
    submitForm() {
      const that = this

      if (this.model.limitNum == 0) {
        that.$message.warning('限购不能为0')
        return;
      }

      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }

          let filter = this.model.priceArray.filter(Boolean)
          if (filter && filter.length > 0) {
            this.model.storeUnitPrice = JSON.stringify(filter)
          } else {
            this.model.storeUnitPrice = ''
            // this.$message.warning('请输入门店菜品合作单价')
          }

          this.model.hcSiteRelationList = this.siteArray
          this.model.businessHours = JSON.stringify(this.model.businessHoursArray)

          // 平台描述
          this.model.desList = this.model.desList_label.split('/')

          console.log('保存商户数据：')
          console.log(JSON.parse(JSON.stringify(this.model)))
          
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },

    // 大厦的启用与关闭---确定按钮也执行了保存
    changeBuildCactivation(item) {
      return;
      let url = 'hc/hcAddressMerchantRelation/edit'
      httpAction(url, item, 'post')
        .then((res) => {
          if (res.success) {
            console.log('成功：修改大厦是否启用状态');
          }
        })
    },

    // 点击大厦名称，弹窗显示详情
    clickAddressDetailsName(item) {
      console.log(item);
      this.addressDetail.addressId = item.addressDetailsId;
      this.addressDetail.merchantId = item.merchantId;
      this.addressDetail.addressName = item.addressDetailsName;
      this.addressDetail.show = true;
    },

    // 点击大厦弹窗
    handleCloseDetailModal() {
      this.addressDetail.show = false;
    },

  },
}
</script>
<style lang="scss" scoped>
.siteActive {
  color: #62a5ed;
}
.hmf-item-addressMerchantRelations {
  display: flex;
  &:hover {
    background-color: #c5e7f6;
  }
  .edifice {
    margin: 0px 50px;
    min-width: 276px;
    cursor: pointer;
  }
  .business {
    margin-right: 10px;
  }
  .ant-time-picker {
    width: 90px;
  }
}
</style>